package com.pig4cloud.pig.ads.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pig.ads.pig.mapper.AdCommonWordsMapper;
import com.pig4cloud.pig.ads.service.AdAccountService;
import com.pig4cloud.pig.ads.service.AdCommonWordsService;
import com.pig4cloud.pig.api.dto.AdCommonWordsDto;
import com.pig4cloud.pig.api.entity.AdAccount;
import com.pig4cloud.pig.api.entity.AdCommonWordsEntity;
import com.pig4cloud.pig.api.vo.AdAccountVo;
import com.pig4cloud.pig.api.vo.AdCommonWordsVO;
import com.pig4cloud.pig.common.core.constant.CommonConstants;
import com.pig4cloud.pig.common.core.constant.enums.PlatformTypeEnum;
import com.pig4cloud.pig.common.core.util.R;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class AdCommonWordsServiceImpl extends ServiceImpl<AdCommonWordsMapper, AdCommonWordsEntity> implements AdCommonWordsService {

	//	private final AdvService advService;
	private final AdAccountService adAccountService;

	/**
	 * 常用语列表
	 *
	 * @param words
	 * @return
	 */
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	@Override
	public List<AdCommonWordsEntity> getWordsList(AdCommonWordsVO words) {
		LambdaQueryWrapper<AdCommonWordsEntity> queryWrapper = Wrappers.<AdCommonWordsEntity>lambdaQuery().eq(AdCommonWordsEntity::getIsDeleted, 0);
		// 获取当前用户拥有的广告账户
//		Set<String> advertiserIds = advService.getAccountList(Integer.parseInt(PlatformTypeEnum.TT.getValue()), null).stream().map(AdAccount::getAdvertiserId).collect(Collectors.toSet());
		Set<String> advertiserIds = adAccountService.getAccountsByAuthorize(new AdAccountVo().setMediaCode(PlatformTypeEnum.TT.getValue())).stream().map(AdAccount::getAdvertiserId).collect(Collectors.toSet());
		if (CollectionUtil.isEmpty(advertiserIds)) {
			// 当前帐户下没有广告账户
			return Collections.emptyList();
		}
		if (StringUtils.isNotEmpty(words.getAdvertiserId())) {
			if (advertiserIds.contains(words.getAdvertiserId())) {
				advertiserIds = Collections.singleton(words.getAdvertiserId());
			} else {
				return Collections.emptyList();
			}
		}
		queryWrapper.in(AdCommonWordsEntity::getAdvertiserId, advertiserIds).eq(AdCommonWordsEntity::getIsDeleted, 0).like(StringUtils.isNotEmpty(words.getAdvertiserName()), AdCommonWordsEntity::getAdvertiserName, words.getAdvertiserName()).orderByDesc(AdCommonWordsEntity::getCreateDate);
		return baseMapper.selectList(queryWrapper);
	}

	/**
	 * 常用语分页列表
	 *
	 * @param words
	 * @return
	 */
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	@Override
	public Page<AdCommonWordsEntity> getWordsPage(AdCommonWordsVO words) {
		LambdaQueryWrapper<AdCommonWordsEntity> queryWrapper = Wrappers.<AdCommonWordsEntity>lambdaQuery().eq(AdCommonWordsEntity::getIsDeleted, 0);

		// 获取当前用户拥有的广告账户
//		Set<String> advertiserIds = advService.getAccountList(Integer.parseInt(PlatformTypeEnum.TT.getValue()), null).stream().map(AdAccount::getAdvertiserId).collect(Collectors.toSet());
		Set<String> advertiserIds = adAccountService.getAccountsByAuthorize(new AdAccountVo().setMediaCode(PlatformTypeEnum.TT.getValue())).stream().map(AdAccount::getAdvertiserId).collect(Collectors.toSet());
		if (CollectionUtil.isEmpty(advertiserIds)) {
			// 当前帐户下没有广告账户
			return new Page<AdCommonWordsEntity>().setTotal(0).setCurrent(words.getCurrent()).setSize(words.getSize()).setRecords(Collections.emptyList());
		}
		if (StringUtils.isNotEmpty(words.getAdvertiserId())) {
			if (advertiserIds.contains(words.getAdvertiserId())) {
				advertiserIds = Collections.singleton(words.getAdvertiserId());
			} else {
				return new Page<AdCommonWordsEntity>().setTotal(0).setCurrent(words.getCurrent()).setSize(words.getSize()).setRecords(Collections.emptyList());
			}
		}
		queryWrapper.in(AdCommonWordsEntity::getAdvertiserId, advertiserIds).eq(AdCommonWordsEntity::getIsDeleted, 0).like(StringUtils.isNotEmpty(words.getAdvertiserName()), AdCommonWordsEntity::getAdvertiserName, words.getAdvertiserName()).orderByDesc(AdCommonWordsEntity::getCreateDate);
		return baseMapper.selectPage(words, queryWrapper);
	}

	/**
	 * 添加常用语信息
	 *
	 * @param words
	 */
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ, rollbackFor = Exception.class)
	@Override
	public void addWords(AdCommonWordsVO words) {
		if (this.count(Wrappers.<AdCommonWordsEntity>lambdaQuery().eq(AdCommonWordsEntity::getAdvertiserId, words.getAdvertiserId()).eq(AdCommonWordsEntity::getIsDeleted, 0)) >= 20) {
			// 每个广告账号常用语不允许超过20个
			throw new IllegalStateException("每个广告账号常用语不允许超过20个");
		}
		if (this.count(Wrappers.<AdCommonWordsEntity>lambdaQuery().eq(AdCommonWordsEntity::getAdvertiserId, words.getAdvertiserId()).eq(AdCommonWordsEntity::getText, words.getText()).eq(AdCommonWordsEntity::getIsDeleted, 0)) >= 1) {
			// 当前广告账户下已添加该常用语
			throw new IllegalStateException("当前广告账户下已添加该常用语");
		}
		this.save(new AdCommonWordsEntity().setAdvertiserId(words.getAdvertiserId()).setAdvertiserName(words.getAdvertiserName()).setText(words.getText()).setCreateDate(new Date()).setUpdateDate(new Date()));
	}

	/**
	 * 编辑常用语
	 *
	 * @param words
	 */
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ, rollbackFor = Exception.class)
	@Override
	public void editWords(AdCommonWordsVO words) {
		AdCommonWordsEntity entity = this.getById(words.getId());
		if (null == entity) {
			return;
		}
		String advertiserId = entity.getAdvertiserId();
		LambdaUpdateWrapper<AdCommonWordsEntity> updateWrapper = Wrappers.lambdaUpdate();
		// 校验是否需要修改advertiserId
		if (StringUtils.isNotEmpty(words.getAdvertiserId()) && !words.getAdvertiserId().equals(entity.getAdvertiserId())) {
			if (this.count(Wrappers.<AdCommonWordsEntity>lambdaQuery().eq(AdCommonWordsEntity::getAdvertiserId, words.getAdvertiserId()).eq(AdCommonWordsEntity::getIsDeleted, 0)) >= 20) {
				// 每个广告账号常用语不允许超过20个
				throw new IllegalStateException("每个广告账号常用语不允许超过20个");
			}
			updateWrapper.set(AdCommonWordsEntity::getAdvertiserId, advertiserId = words.getAdvertiserId());
		}
		// 校验是否需要修改advertiserName
		updateWrapper.set(StringUtils.isNotEmpty(words.getAdvertiserName()) && !words.getAdvertiserName().equals(entity.getAdvertiserName()), AdCommonWordsEntity::getAdvertiserName, words.getAdvertiserName());
		// 校验是否需要修改text
		if (StringUtils.isNotEmpty(words.getText()) && !words.getText().equals(entity.getText())) {
			if (this.count(Wrappers.<AdCommonWordsEntity>lambdaQuery().eq(AdCommonWordsEntity::getAdvertiserId, advertiserId).eq(AdCommonWordsEntity::getText, words.getText()).eq(AdCommonWordsEntity::getIsDeleted, 0)) >= 1) {
				// 当前广告账户下已添加该常用语
				throw new IllegalStateException("当前广告账户下已添加该常用语");
			}
			updateWrapper.set(AdCommonWordsEntity::getText, words.getText());
		}
		if (StringUtils.isEmpty(updateWrapper.getSqlSet())) {
			return;
		}
		this.update(updateWrapper.set(AdCommonWordsEntity::getUpdateDate, new Date()).eq(AdCommonWordsEntity::getId, words.getId()));
	}


	@Deprecated
	@Override
	@Transactional
	public R insert(AdCommonWordsDto dto) {
		List<AdCommonWordsEntity> adCommonWordsEntityList = baseMapper.selectList(Wrappers.<AdCommonWordsEntity>query().lambda().eq(AdCommonWordsEntity::getAdvertiserId, dto.getAdvertiser_id()).eq(AdCommonWordsEntity::getIsDeleted, CommonConstants.STATUS_NORMAL));
		if (CollectionUtils.isNotEmpty(adCommonWordsEntityList)) {
			if (adCommonWordsEntityList.size() >= 20) {
				return R.failed("每个广告账号常用语不允许超过20个");
			} else {
				List<String> textList = adCommonWordsEntityList.stream().map(s -> s.getText()).collect(Collectors.toList());
				if (textList.contains(dto.getText())) {
					return R.failed("当前账号已添加该常用语，请核实后再添加");
				}
			}
		}
		AdCommonWordsEntity entity = new AdCommonWordsEntity();
		BeanUtils.copyProperties(dto, entity);
		entity.setAdvertiserId(dto.getAdvertiser_id());
		entity.setAdvertiserName(dto.getAdvertiser_name());
		Integer r = baseMapper.insert(entity);
		if (r <= 0) {
			return R.failed("新增失败");
		}
		return R.ok("", "保存成功！");
	}

	@Deprecated
	@Override
	@Transactional
	public R update(AdCommonWordsDto dto) {
		List<AdCommonWordsEntity> adCommonWordsEntityList = baseMapper.selectList(Wrappers.<AdCommonWordsEntity>query().lambda().eq(AdCommonWordsEntity::getAdvertiserId, dto.getAdvertiser_id()).eq(AdCommonWordsEntity::getIsDeleted, CommonConstants.STATUS_NORMAL));
		adCommonWordsEntityList = adCommonWordsEntityList.stream().filter(t -> !t.getId().equals(dto.getId())).collect(Collectors.toList());
		if (CollectionUtils.isNotEmpty(adCommonWordsEntityList)) {
			if (adCommonWordsEntityList.size() >= 20) {
				return R.failed("每个广告账号常用语不允许超过20个");
			} else {
				adCommonWordsEntityList = adCommonWordsEntityList.stream().filter(t -> dto.getText().equals(t.getText())).collect(Collectors.toList());
				if (CollectionUtils.isNotEmpty(adCommonWordsEntityList)) {
					return R.failed("当前账号已已存在该常用语，请核实后再修改");
				}
			}
		}
		AdCommonWordsEntity entity = new AdCommonWordsEntity();
		BeanUtils.copyProperties(dto, entity);
		entity.setAdvertiserId(dto.getAdvertiser_id());
		entity.setAdvertiserName(dto.getAdvertiser_name());
		Integer r = baseMapper.updateById(entity);
		if (r <= 0) {
			return R.failed("修改失败");
		}
		return R.ok("", "保存成功！");
	}

	@Deprecated
	@Override
	public IPage<AdCommonWordsEntity> selectPageList(AdCommonWordsDto dto) {
//		Integer userId = SecurityUtils.getUser().getId();
		//获取当前账号下 广告账户列表
//		List<String> advertiserIds = advService.getOwnerAdv(userId, PlatformTypeEnum.TT.getValue());
		List<String> advertiserIds = adAccountService.getAccountsByAuthorize(new AdAccountVo().setMediaCode(PlatformTypeEnum.TT.getValue())).stream().map(AdAccount::getAdvertiserId).collect(Collectors.toList());
		if (CollectionUtils.isEmpty(advertiserIds)) {
			return new Page();
		}
		dto.setAdvertiserIds(advertiserIds);
		return baseMapper.selectPageList(dto);
	}

	@Deprecated
	@Override
	@Transactional
	public R delete(Long id) {
		Integer r = baseMapper.deleteById(id);
		if (r <= 0) {
			return R.failed("删除失败");
		}
		return R.ok("", "操作成功！");
	}
}
